<template>
  <view class="my-search-box">
    <uni-search-bar @input="inputValue" @confirm="searchVal" @close="closeBtn"></uni-search-bar>
    <view class="search-result" v-if="keyVal !== ''">
      <view class="search-resul-title" v-for="resultItem in searchResult" :key="resultItem.goods_id">
        <text class="search-title" >
          {{resultItem.goods_name}}
        </text>
        <view class="iconfont icon-chevron-right"></view>
      </view>
      <view v-if="searchResult.length === 0 && notVal" class="not-result">
        无结果
      </view>
    </view>
    <view class="search-history" v-else>
      <view class="history-edit">
        <text>搜索历史</text>
        <button 
        v-if="!editClose" 
        class="edit-btn" 
        size="mini" 
        plain="true" 
        @click="editHistory"
        >编辑</button>
        <view class="edit-btn-box" v-else>
          <button class="edit-btn" size="mini" type="primary" @click="cleanHistory">清空 <view class="iconfont "></view></button>
          <button class="edit-btn" size="mini" plain="true" @click="editHistory">完成</button>
        </view>
      </view>
      <view class="search-history-box">
        <view class="history-title" v-for="(historyItems, i) in historys" :key="historyItems">
          <text @click="gotoGoodsList(historyItems)" v-if="!editClose">{{historyItems}}</text>
          <text @click="deleteHistory(historyItems)" v-else >{{historyItems}}</text>
          <view class="iconfont icon-close-circle" v-if="editClose"></view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
  import { onReady } from '@dcloudio/uni-app'
  import {ref,computed} from 'vue'
  const keyVal = ref('')
  const notVal = ref(false)
  const searchResult =  ref([]) // 存储搜索结果的数组
  onReady(() => {
    historyList.value = JSON.parse(uni.getStorageSync('searchHistory') || '[]')
  })
  // 获取输入框实时输入的值
  let timer = null
  const inputValue = (event) => {
    clearTimeout(timer)
    if(event !== '') {
      timer = setTimeout(() => {
        keyVal.value = event
        getSearchResult()
      }, 1000)
    } else {
      keyVal.value = ''
    }
  }
  
  const getSearchResult = async () => {
    if(keyVal.value === '') {
      searchResult.value = []
      notVal.value = false
      return
    }
    const {data} = await uni.$http.get('/api/public/v1/goods/qsearch', {query: keyVal.value})
    if (data.meta.status !== 200) return 
    searchResult.value = data.message
    saveSearchHistory()
    notVal.value = true
  }
  
  // 获取点击搜索后的值
  const searchVal = (event) => {
    console.log(event);
  }
  const closeBtn = (event) => {
    uni.navigateBack({
    	delta: 2
    })
  }
  
  // 编辑历史删除
  const editClose = ref(false)
  const editHistory = () => {
    editClose.value = !editClose.value
  }
  // 获取搜索历史
  const historyList = ref([])
  const saveSearchHistory = () =>{
    // historyList.value.push(keyVal.value)
    const set = new Set(historyList.value)
    // 可以调用delete方法删除对应的记录
    set.delete(keyVal.value)
    // 使用add 方法往set添加记录
    set.add(keyVal.value)
    // 将 set对象转为数组
    historyList.value = Array.from(set)
    // 本地存储数据 持久化
    uni.setStorageSync('searchHistory', JSON.stringify(historyList.value))
  }
  
  // 倒序添加搜索记录
  const historys = computed(() => {
     return [...historyList.value].reverse()
  })
  // 清空历史记录
  const cleanHistory = () => {
    historyList.value = []
    uni.setStorageSync('searchHistory', '[]')
    editClose.value = false
  }
  // 跳转到商品类表
  const gotoGoodsList = (val) => {
    uni.navigateTo({
      url: '/subpkg/goods_list/goods_list?query=' + val
    })
  }
  
  const deleteHistory = (options) => {
    historyList.value.splice(historyList.value.indexOf(options), 1)
    uni.setStorageSync('searchHistory', JSON.stringify(historyList.value))
  }
</script>

<style lang="scss">
.search-result {
  .search-resul-title {
    position: relative;
    display: flex;
    flex-direction: column;
    .search-title {
      border-bottom: 1rpx solid #999;
      margin: 0 28rpx;
      padding: 25rpx 0;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .icon-chevron-right {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
      font-size: 45rpx;
      margin: 0 8rpx;
    }
  }
  .not-result {
    height: 150rpx;
    line-height: 150rpx;
    text-align: center;
    font-size: 35rpx;
    color: #999;
  }
}
.search-history {
  display: flex;
  flex-direction: column;
  .history-edit {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 80rpx;
    padding: 0 20rpx;
    border: 1rpx solid #f5f5f5;
    box-sizing: border-box;
    .edit-btn {
      height: 50rpx;
      line-height: 50rpx;
      margin: 0;
      margin-right: 10rpx;
      padding: 0 10rpx;
    }
  }
  .search-history-box {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    margin-top: 20rpx;
    padding: 0 10rpx;
    .history-title {
      position: relative;
      display: inline-block;
      min-width: 40rpx;
      height: 30rpx;
      line-height: 30rpx;
      text-align: center;
      background-color: #f5f5f5;
      margin-left: 30rpx;
      margin-bottom: 30rpx;
      padding:8rpx 20rpx;
      border-radius: 15px;
      .icon-close-circle {
        position: absolute;
        top: -8rpx;
        right: -4rpx;
      }
    }
  }
}
</style>
